package pl.maliboo.ftp
{
	public class FTPFile
	{
		/**
		 * for WAT platform
		 * store the playlist id corresponding to this folder
		 * read in .defaults.ini file by WatUploaderApplication
		 */
		public var playlistid:String;
		
		public var _name:String;
		public var _path:String;
		public var _size:int;
		public var _date:Date;
		public var _isDir:Boolean;
		public function FTPFile (name:String="",
								path:String="", 
								size:int=0,
								date:Date=null,
								isDir:Boolean=false)
		{
			_name = name;
			_path = path;
			_size = size;
			_date = date;
			_isDir = isDir;
		}
		
		public function get fullPath ():String
		{
			// TF1
			return (name.length == 0 ) ? path : path + "/" + name;
		}
		
		public function get name ():String
		{
			return _name;
		}
		
		public function get path ():String
		{
			return _path;
		}
		
		public function get size ():int
		{
			return _size;
		}
		
		public function get date ():Date
		{
			return new Date(date);
		}
		public function get isDir ():Boolean
		{
			return _isDir;
		}
		
		public static function parseFromListEntry (entry:String, dir:String):FTPFile
		{
			// TF1 : fonction réécrite
			var fields:Array = entry.split(/ +/g, 8);
			
			var infos:Object = {
				rights:		fields[0].toLowerCase(),
				unknown:	fields[1],
				owner:		fields[2],
				group:		fields[3],
				size:		parseInt(fields[4]),
				month:		fields[5],
				day:		fields[6],
				year:		(fields[7].match(/:/)) ? new Date().fullYear : fields[7],
				hour:		(fields[7].match(/:/)) ? fields[7] : "00:00",
				fullDate:	new Date(),
				filename:	getFilename(entry, fields),
				isDir:		fields[0].charAt(0) == "d",
				path:		dir
			};

			return new FTPFile(infos.filename,
								infos.path,
								infos.size,
								infos.fullDate,
								infos.isDir);
		}
		
		private static function getFilename(entry:String, fields:Array):String {
			for each (var field:String in fields) {
				entry = entry.substring(field.length, entry.length);
				entry = entry.replace(/^ +/, "");
			}
			
			return entry;
		}
		
		public static function parseFormListing (listing:String, dir:String, stripDot:Boolean=true):Array
		{
			// TF1 : fonction réécrite
			var tmp:Array = listing.match(/^.+/gm);
			var list:Array = new Array();

			for each (var file:String in tmp) {
				if (file.split(/ +/g).length > 8) {
					var ftpFile:FTPFile = parseFromListEntry(file, dir);
					
					list.push(parseFromListEntry(file, dir));
				}
			}
			
			/*if (stripDot) {
				if ((list[list.length-1] as FTPFile).name) {
					list.pop();
				}
			}*/
			
			return list;
		}
	}
}